#include <stdio.h>
#include <string.h>
#include <unistd.h>

#include "md5.h"

extern char *getlic(char *key);
char* rtrim(char *str)
{
     int i;
     int len=strlen(str);
     for(i=len-1;i>=0;i--)
 		if(str[i]==' ' || str[i] == '\n')
            str[i]= '\0';
         else
            break;
     return str;
}

int main()
{
	static char linestr[1024], key[1024];
	const char key1[]="SEAN&YANG"; const char key2[]="SunRIbO";
	int i = 0;
	FILE * fp = NULL;
	char *ptr = NULL;
	static char value[128];
	static char license[128], ip[32], expiration[32], version[4], signature[128];

	fp = fopen(  "lic.txt", "r") ;
	if( fp == NULL ) return -1;

	while( fgets(linestr, 1024, fp) ) {
		if( ptr = strstr( linestr, "LICENSE=" ) ) {
			strcpy( value, ptr+strlen("LICENSE=") );
			strcpy( license, rtrim(value) );
		}
		if( ptr = strstr( linestr, "IP=" ) ) {
			strcpy( value, ptr+strlen("IP=") );
			strcpy( ip, rtrim(value) );
		}
		if( ptr = strstr( linestr, "EXPIRATION=" ) ) {
			strcpy( value, ptr+strlen("EXPIRATION=") );
			strcpy( expiration, rtrim(value) );
		}
		if( ptr = strstr( linestr, "VERSION=" ) ) {
			strcpy( value, ptr+strlen("VERSION=") );
			strcpy( version, rtrim(value) );
		}
		if( ptr = strstr( linestr, "SIGNATURE=" ) ) {
			strcpy( value, ptr+strlen("SIGNATURE=") );
			strcpy( signature, rtrim(value) );
		}
	}
	fclose(fp);

	memset( linestr, 0, 1024 );
	sprintf( linestr, "%s%s%s%s%s", key2, license, ip, expiration, version );
	printf("linestr=%s\n", linestr) ;
	strcpy( key, getlic(linestr) );
	printf( "true signature is [%s]\n", key );
	printf( "signature is [%s]\n", signature );
	if( strcmp( key, signature ) ==0  ) 
		printf( "signature is right!\n" );

	return 1;
}

char *getlic(char *str)
{
     struct MD5Context md5c;
     static unsigned char ss[16];
     static char str1[33]="";
     int i;

     MD5Init( &md5c );
     MD5Update( &md5c, str, strlen(str) );
     MD5Final( ss, &md5c );

     for( i=0; i<16; i++ ) {
          sprintf(str1+i*2, "%02X", ss[i]);
     }
  	 return str1;
}
